/*
 * @Description: 驰领信息科技
 * @Author: siyuankang
 * @Date: 2019-10-16 21:48:04
 * @LastEditTime: 2020-04-22 16:30:03
 * @LastEditors: Please set LastEditors
 */
(function(window) {
    var cl = {};

    //基础参数定义
    // cl.apiServer = 'https://test.vtom.top/app/index.php?i=7&c=entry&m=ruike_books&do=api'; //线上地址
   cl.apiServer = 'https://tkapi.s775775.cn/'; //测试地址
   cl.sina = 'fc2020';



    //  cl.apiServer = 'http://192.168.0.103:8076/';

    // cl.apiServer = 'http://192.168.0.75:8088/app/'; //本地
    // cl.fileSever = 'http://192.168.0.75:8088/'; //本地

    cl.AliossUrl = 'http://xjfb.oss-cn-hangzhou.aliyuncs.com/'; //阿里oss
    /**
     * @author- 驰领信息科技
     * [服务端返回状态标准码，前后端开发人员务必严格遵守此套状态码]
     * SUCCESS("200", "成功!"),
     * BODY_NOT_MATCH("400","请求的数据格式不符!"),
     * SIGNATURE_NOT_MATCH("401","请求的数字签名不匹配!"),
     * NOT_FOUND("404", "未找到该资源!"),
     * INTERNAL_SERVER_ERROR("500", "服务器内部错误!"),
     * SERVER_BUSY("503","服务器正忙，请稍后再试!")
     * @type {[return]}
     */

    /**
     *  @author- 驰领信息科技
     * [restful接口返回格式,前后端开发人员务必严格遵守此套格式]
     * @code: 后端返回状态码
     * @message: 后端返回信息
     * @result: 后端返回数据
     * {
     *     "code": "code",
     *     "message": "message",
     *     "result": "data"
     * }
     * @type {[type]}
     */
    //svn配置测试
    cl.svn = '';
    /**
     * [用户登录信息（全局直接使用不需要再定义）]
     * @type {[type]}
     */
    //用户登录令牌
    $api.getStorage('userToken') ? cl.userToken = $api.getStorage('userToken') : cl.userToken = '';
    //用户登录id
    $api.getStorage('mid') ? cl.mid = $api.getStorage('mid') : cl.mid = '';
    //用户登录信息
    $api.getStorage('userInfo') ? cl.userInfo = $api.getStorage('userInfo') : cl.userInfo = '';
    // 推送状态
    $api.getStorage('jpushStatus') ? cl.jpushStatus = $api.getStorage('jpushStatus') : cl.jpushStatus = '';
    // 语言包
    $api.getStorage('LanguageStatus') ? cl.LanguageStatus = $api.getStorage('LanguageStatus') : cl.LanguageStatus = '';

    //页面错语提示信息定义
    cl.noMore = '<div class="aui-margin-10 aui-text-center"><div class="aui-label aui-margin-10">没有更多了</div></div>';
    cl.noList = '<div class="errinfo"><img src="../image/nolist.png"/><br/>暂无数据</div>';
    cl.noNet = '<div class="errinfo"><img src="../image/nonet.png"/><br/>数据载入失败</div>';
    cl.ClipImageUrl = '?x-oss-process=image/resize,m_fill,h_200,w_200,limit_0'; //图片裁剪
    cl.ThumbImageUrl = '?x-oss-process=image/resize,p_20'; //图片等比缩放
    cl.AvartUrl = '?x-oss-process=image/resize,m_fill,h_100,w_100,limit_0';
    //设备和系统信息
    cl.deviceInfo = function() {
        return {
            appVersion: api.appVersion, //应用版本号
            systemType: api.systemType, //系统类型
            systemVersion: api.systemVersion, //系统版本
            deviceId: api.deviceId, //设备唯一标识
            deviceModel: api.deviceModel, //设备型号
            operator: api.operator, //设备名称
            safeArea: api.safeArea.bottom //适配iPhone X
        }
    }
    cl.systemType = function(){
        if(api.systemVersion=='ios'){
          return 2;
        }else{
          return 1;
        }
    }
    //通用页面初始执行项
    //@param refresh       是否注册下拉刷新
    //@param scrollBottom  是否注册上拉加载
    //@param callback      处理右边按钮执行
    cl.apiready = function(refresh, scrollBottom, callback) {
        //点击返回按钮
        api.addEventListener({
            name: 'navbackbtn'
        }, function(ret, err) {
            api.closeWin();
        });
        if (api.systemType == 'ios') {
            api.setStatusBarStyle({
                style: 'dark'
            });
        }

        //点击右边功能按钮
        api.addEventListener({
            name: 'navitembtn'
        }, function(ret, err) {
            if (ret.type == 'left') {
                api.closeWin();
            } else if (ret.type == 'right') {
                if (typeof callback === "function") {
                    callback(ret, err);
                }
            }
        });
        //是否注册下拉刷新
        if (refresh) {
            cl.openRefresh()
        }

        //是否注册上拉加载
        if (scrollBottom) {
            cl.scrollBottom()
        }

        /**
         * [页面初始化调用]
         * @author [司远康 2019-07-06]
         */
        if (api.connectionType == 'none') {
            api.alert({
                title: '提示',
                msg: '您的网络开小差了，请稍后再试！',
            }, function(ret, err) {
                return;
            });
        }

        header = $api.byId('header');
        if (header) {
            $api.fixIos7Bar(header);
            $api.fixStatusBar(header);
            headerHeight = $api.offset(header).h;
        }

        footer = $api.byId('footer');
        if (footer) {
            $api.fixTabBar($api.byId('footer'));
            footerHeight = $api.offset(footer).h;
        }
        api.parseTapmode();
    }

    //打开新的窗口
    //@param name       窗口文件名，不带文件后缀
    //@param pageParam  需传递JSON对象
    cl.openWin = function(params) {
        /**
         * [页面初始化调用]
         * @author [司远康 2019-07-06]
         */
        if (api.connectionType == 'none') {
            api.alert({
                title: '提示',
                msg: '您的网络开小差了，请稍后再试！',
            }, function(ret, err) {
                return;
            });
        }
        api.openWin({
            name: params.name.match(/[^\/]*$/)[0],
            url: params.name + '.html',
            softInputBarEnabled: params.softInputBarEnabled || false,
            slidBackEnabled: params.slidBackEnabled || true,
            bounces: params.bounces || false,
            bgColor: params.bgColor || '#f1f1f1',
            reload: params.reload || false,
            pageParam: params.pageParam || {},
            rect: {
                marginBottom: api.safeArea.bottom || 0, // main页面距离win底部的高度
            },
        });
    };
    //打开新的窗口
    //@param name       窗口文件名，不带文件后缀
    //@param pageParam  需传递JSON对象
    cl.openWinNoSlidBack = function(params) {
        /**
         * [页面初始化调用]
         * @author [司远康 2019-07-06]
         */
        if (api.connectionType == 'none') {
            api.alert({
                title: '提示',
                msg: '您的网络开小差了，请稍后再试！',
            }, function(ret, err) {
                return;
            });
        }
        api.openWin({
            name: params.name.match(/[^\/]*$/)[0],
            url: params.name + '.html',
            softInputBarEnabled: params.softInputBarEnabled || false,
            slidBackEnabled: false,
            bounces: params.bounces || false,
            bgColor: params.bgColor || '#f1f1f1',
            reload: params.reload || false,
            pageParam: params.pageParam || {},
            rect: {
                marginBottom: api.safeArea.bottom || 0, // main页面距离win底部的高度
            },
        });
    };
    //打开需会员身份验证的新窗口
    cl.loginOpenWin = function(params) {
        if (!cl.userInfo) {
            cl.openWin({
                name: 'login',
                slidBackEnabled: false, //是否允许右滑关闭
                pageParam: params.pageParam || {}
            })
        } else {
            cl.openWin(params);
        }
    }

    //关闭当前窗口
    cl.closeWin = function(params) {
        if (params.name) {
            api.closeWin({
                name: params.name
            });
        } else {
            api.closeWin();
        }
    }

    //关闭除目标的所有窗口
    cl.closeToWin = function(params) {
        if (!params.name) {
            params.name = 'root';
        }
        api.closeToWin({
            name: params.name
        });
    }

    //打开标准Frame
    //@param name       Frame文件名，不带文件后缀
    //@param pageParam  需传递JSON对象
    //@param header     标题的dom对象，用于获取高度
    cl.openFrame = function(params) {
        // alert(JSON.stringify(params));
        var headerH = params.header ? $api.offset(params.header).h : 0;
        var footerH = params.footer ? $api.offset(params.footer).h : 0;
        api.openFrame({
            name: params.name.match(/[^\/]*$/)[0],
            url: params.name + '.html',
            bounces: params.bounces || false,
            rect: {
                marginTop: headerH, // main页面距离win顶部的高度
                // marginBottom: footerH ,
                marginBottom: footerH + (api.safeArea.bottom || 0), // main页面距离win底部的高度
                w: 'auto' // main页面的宽度 自适应屏幕宽度
            },
            pageParam: params.pageParam || {},
            allowEdit: true,
            bgColor: params.bgColor || '#fff'
        });
    }

    //关闭当前Frame
    cl.closeFrame = function(params) {
        if (params.name) {
            api.closeFrame({
                name: params.name
            });
        } else {
            api.closeFrame();
        }
    }

    //打开带标题栏的窗口
    //@param name       窗口文件名，不带文件后缀
    //@param title      窗口标题文本
    //@param rightButton右侧图片按钮，add添加图片，more更多图片，或指定图片地址
    //@param pageParam  需传递JSON对象
    cl.openNavWin = function(params) {
            var winparam = {
                    name: params.name.match(/[^\/]*$/)[0],
                    url: params.name + '.html',
                    softInputBarEnabled: params.softInputBarEnabled || false,
                    slidBackEnabled: params.slidBackEnabled || true,
                    bounces: params.bounces || false,
                    bgColor: params.bgColor || '#f5f5f5',
                    reload: params.reload || false,
                    pageParam: params.pageParam || {},

                    title: params.title || '',
                    navigationBar: {}
                }
                //是否配置标题样式
            if (params.nav) {
                winparam.navigationBar = {
                    backgroud: params.nav.backgroud || '#fff',
                    shadow: params.nav.shadow || '#ddd',
                    color: params.nav.color || '#000',
                    fontSize: params.nav.fontSize || '17',
                }
            }
            //左边后退按钮
            if (params.leftButton) {
                winparam.navigationBar.leftButtons = [{
                    iconPath: 'widget://image/left_back.png'
                }]
            } else {
                winparam.navigationBar.hideBackButton = true
            }
            //右边更多按钮
            if (params.rightButton == 'more') {
                winparam.navigationBar.rightButtons = [{
                    iconPath: 'widget://image/right_more.png'
                }]
            }
            //右边添加按钮
            else if (params.rightButton == 'add') {
                winparam.navigationBar.rightButtons = [{
                    iconPath: 'widget://image/right_add.png'
                }]
            }
            //自定义右侧按钮图片
            else if (params.rightButton) {
                winparam.navigationBar.rightButtons = [{
                    iconPath: params.rightButton
                }]
            }
            api.openTabLayout(winparam);
        }
        //默认AJAX通用处理,异步返回数据,不需要加载小菊花
    cl.defaultAjax = function(params, callback) {
            // console.log(cl.apiServer+ params.apiName+params.method+JSON.stringify(params.apiParam));
            api.ajax({
                url: cl.apiServer + params.apiName,
                method: params.method || 'post',
                timeout: params.timeout || 30,
                dataType: 'json',
                headers: {
                    token: params.token || '',
                },
                data: {
                    values: params.apiParam || {},
                    files: params.files || {}
                }
            }, function(ret, err) {
                cl.closeRefresh();
                cl.closeLoading();
                if (ret) {
                    if (ret.code == '401') {
                        // cl.LogBack();
                    } else if (ret.code == '500') {
                        api.toast({
                            msg: '服务器异常，请重试',
                            duration: 2000,
                            location: 'bottom'
                        });
                        return;
                    } else if (ret.code == '203') {
                        api.toast({
                            msg: ret.message,
                            duration: 2000,
                            location: 'bottom'
                        });
                        return;
                    } else if (ret.code == '200') {
                        if (typeof callback === "function") {
                            callback(ret);
                        }
                    } else if (ret.url) {
                        callback(ret);
                    }
                } else {
                    if (typeof callback === "function") {
                        api.toast({
                            msg: '网络异常',
                            duration: 2000,
                            location: 'bottom'
                        });
                    }
                }
            });
        }
        //默认AJAX通用处理,异步返回数据,不需要加载小菊花
    cl.defaultajax = function(params, callback) {
            // console.log(cl.apiServer+ params.apiName+params.method+JSON.stringify(params.apiParam));
            api.ajax({
                url: cl.apiServer + params.apiName,
                method: params.method || 'post',
                timeout: params.timeout || 30,
                dataType: 'json',
                headers: {
                    token: params.token || '',
                },
                data: {
                    values: params.apiParam || {},
                    files: params.files || {}
                }
            }, function(ret, err) {
                cl.closeRefresh();
                cl.closeLoading();
                if (ret) {
                    if (ret.code == '401') {
                        // cl.LogBack();
                    } else if (ret.code == '500') {
                        api.toast({
                            msg: '服务器异常，请重试',
                            duration: 2000,
                            location: 'bottom'
                        });
                        return;
                    } else if (ret.code == '-1') {
                        api.toast({
                            msg: ret.message,
                            duration: 2000,
                            location: 'bottom'
                        });
                        return;
                    } else if (ret.code == '200') {
                        if (typeof callback === "function") {
                            callback(ret);
                        }
                    } else if (ret.url) {
                        callback(ret);
                    }
                } else {
                    if (typeof callback === "function") {
                        api.toast({
                            msg: '网络异常',
                            duration: 2000,
                            location: 'bottom'
                        });
                    }
                }
            });
        }
        //AJAX通用处理 异步返回数据
    cl.ajax = function(params, callback) {
        if (!params.hideLoading) {
            cl.openLoading();
        }

        // console.log(cl.apiServer+ params.apiName+params.method+JSON.stringify(params.apiParam));
        api.ajax({
            url: cl.apiServer + params.apiName,
            method: params.method || 'post',
            timeout: params.timeout || 30,
            dataType: params.dataType || '',
            headers: {
                token: params.token || '',
            },
            data: {
                values: params.apiParam || {},
                files: params.files || {}
            }
        }, function(ret, err) {
            // console.log($api.jsonToStr(ret));
            //隐藏加载进度框
            cl.closeLoading();
            cl.closeRefresh();
            if (ret) {
                if (ret.code == '401') {
                    // cl.LogBack();
                } else if (ret.code == '500') {
                    api.toast({
                        msg: '服务器异常，请重试',
                        duration: 2000,
                        location: 'bottom'
                    });
                    return;
                } else if (ret.code == '1') {
                    api.toast({
                        msg: ret.message,
                        duration: 2000,
                        location: 'bottom'
                    });
                    return;
                } else if (ret.code == '200') {
                    if (typeof callback === "function") {
                        callback(ret);
                    }
                } else if (ret.url) {
                    callback(ret);
                }
            } else {
                if (typeof callback === "function") {
                    api.toast({
                        msg: '网络异常',
                        duration: 2000,
                        location: 'bottom'
                    });
                }
            }
        });
    }

    cl.jsonAjax = function(params, callback) {
            // console.log(JSON.stringify(params));
            api.ajax({
                url: cl.apiServer + params.apiName,
                method: params.method || 'post',
                timeout: params.timeout || 30,
                dataType: 'json',
                headers: {
                    "Content-Type": "application/json;charset=utf-8",
                    token: params.token || ''
                },
                data: {
                    body: params.apiParam || {},
                }
            }, function(ret, err) {
                //隐藏加载进度框
                cl.closeLoading();
                cl.closeRefresh();
                if (ret) {
                    if (ret.code == '401') {
                        // cl.LogBack();
                    } else if (ret.code == '500') {
                        api.toast({
                            msg: '服务器异常，请稍后再试',
                            duration: 2000,
                            location: 'bottom'
                        });
                        return;
                    } else {
                        if (typeof callback === "function") {
                            callback(ret, err);
                        }
                    }
                } else {
                    if (err.statusCode == 401) {
                        if (params.token) {
                            // cl.LogBack()
                        }
                    } else {
                        if (typeof callback === "function") {
                            callback(ret, err);
                        }
                    }
                }
            });
        }
        //权限   重新登录
    cl.LogBack = function(content) {
        $api.setStorage('userInfo', null);
        $api.setStorage('userToken', null);
        cl.userInfo = '';
        cl.userToken = '';
        var dialogBox = api.require('dialogBox');
        dialogBox.alert({
            texts: {
                title: '提示',
                content: content,
                leftBtnTitle: '退出',
                rightBtnTitle: '重新登录'
            },
            tapClose: false,
            styles: {
                bg: '#fff',
                w: 270,
                corner: 7,
                title: {
                    marginT: 12,
                    icon: "",
                    iconSize: 40,
                    titleSize: 18,
                    titleColor: "#000"
                },
                content: {
                    marginT: 10,
                    marginB: 14,
                    color: "#888888",
                    size: 15
                },
                left: {
                    marginB: 0,
                    marginL: 0,
                    w: 135,
                    h: 50,
                    corner: 7,
                    bg: '#fff',
                    size: 18,
                    color: '#000000'
                },
                right: {
                    marginB: 0,
                    marginL: 0,
                    corner: 7,
                    w: 130,
                    h: 50,
                    bg: '#fff',
                    size: 18,
                    color: '#FF9014'
                },
                horizontalLine: {
                    color: '#DDDDDD', //（可选项）字符串类型；左右按钮上边横线的颜色，支持rgb、rgba、#；默认：'rgba(245,245,245,0)'
                    height: 1 //（可选项）数字类型；左右边按钮横线的高度；默认：0
                },
                verticalLine: {
                    color: '#DCDEE3', //（可选项）字符串类型；左右按钮中间竖线的颜色，支持rgb、rgba、#；默认：'rgba(245,245,245,0)'
                    width: 1 //（可选项）数字类型；左右边按钮竖线的高度；默认：0
                }
            }
        }, function(ret) {
            var dialogBox = api.require('dialogBox');
            dialogBox.close({
                dialogName: 'alert'
            });
            if (ret.eventType == 'right') {
                api.sendEvent({
                    name: 'logout_success',
                });
                cl.openWin({
                        name: '../html/login/login'
                    })
                    // $api.clearStorage();
                    // api.rebootApp();
                    // $api.setStorage('loginOut', '');
            } else {
                api.closeWidget({
                    id: 'A6032375244230',
                    silent: true,
                    animation: {
                        type: 'flip',
                        subType: 'from_bottom',
                        duration: 500
                    }
                });
            }
        });
        // cl.openAlert({
        //     content: '登录账号异常,请重新登录。',
        //     tapClose: false
        // }, function(ret, err) {
        //     var dialogBox = api.require('dialogBox');
        //     dialogBox.close({
        //         dialogName: 'alert'
        //     });
        //     if (ret.eventType == 'right') {
        //         $api.clearStorage();
        //         api.rebootApp();
        //         $api.setStorage('loginOut', '');
        //     }
        // });
    }
    cl.beReportLogBack = function() {
            $api.setStorage('userInfo', null);
            $api.setStorage('userToken', null);
            cl.userInfo = '';
            cl.userToken = '';
            var dialogBox = api.require('dialogBox');
            dialogBox.alert({
                texts: {
                    title: '提示',
                    content: '您的账号涉嫌发布违规信息,系统暂时封锁了您的账号，详情请致电客服',
                    leftBtnTitle: '退出',
                    rightBtnTitle: '重新登录'
                },
                tapClose: false,
                styles: {
                    bg: '#fff',
                    w: 270,
                    corner: 7,
                    title: {
                        marginT: 12,
                        icon: "",
                        iconSize: 40,
                        titleSize: 18,
                        titleColor: "#000"
                    },
                    content: {
                        marginT: 0,
                        marginB: 14,
                        color: "#888888",
                        size: 15
                    },
                    left: {
                        marginB: 0,
                        marginL: 0,
                        w: 135,
                        h: 50,
                        corner: 7,
                        bg: '#fff',
                        size: 18,
                        color: '#000000'
                    },
                    right: {
                        marginB: 0,
                        marginL: 0,
                        corner: 7,
                        w: 130,
                        h: 50,
                        bg: '#fff',
                        size: 18,
                        color: '#FF9014'
                    },
                    horizontalLine: {
                        color: '#DDDDDD', //（可选项）字符串类型；左右按钮上边横线的颜色，支持rgb、rgba、#；默认：'rgba(245,245,245,0)'
                        height: 1 //（可选项）数字类型；左右边按钮横线的高度；默认：0
                    },
                    verticalLine: {
                        color: '#DCDEE3', //（可选项）字符串类型；左右按钮中间竖线的颜色，支持rgb、rgba、#；默认：'rgba(245,245,245,0)'
                        width: 1 //（可选项）数字类型；左右边按钮竖线的高度；默认：0
                    }
                }
            }, function(ret) {
                var dialogBox = api.require('dialogBox');
                dialogBox.close({
                    dialogName: 'alert'
                });
                if (ret.eventType == 'right' || ret.eventType == 'left') {
                    $api.clearStorage();
                    api.rebootApp();
                    // $api.setStorage('loginOut', '');
                }
            });
        }
        //载入缓存图片
        //使用方法：onload="app.imageCache(this)"
    cl.imageCache = function(el) {
        var imageURL = $api.attr(el, 'data-src');
        if (imageURL) {
            api.imageCache({
                url: imageURL
            }, function(ret, err) {
                if (ret.status) {
                    el.src = ret.url;
                    $api.removeAttr(el, 'data-src');
                }
            });
        }
    }

    //显示底部提示
    cl.toast = function(params) {
        api.toast({
            msg: params.msg,
            duration: 3000,
            location: params.location || 'bottom'
        });
    }

    //弹出信息提示框
    cl.alert = function(params, callback) {
            api.alert({
                title: '提示',
                msg: params
            }, function(ret, err) {
                if (typeof callback === "function") {
                    callback(ret, err);
                }
            });
        }
        //弹出美化信息提示框
    cl.openAlertPro = function(params, callback) {
            var dialogBox = api.require('dialogBox');
            dialogBox.alert({
                texts: {
                    title: params.title || '提示',
                    content: params.content || params,
                    leftBtnTitle: params.leftBtnTitle || '取消',
                    rightBtnTitle: params.rightBtnTitle || '确定'
                },
                tapClose: false,
                styles: {
                    bg: '#fff',
                    w: api.frameWidth - 100,
                    corner: 7,
                    title: {
                        marginT: 12,
                        icon: params.icon || "",
                        iconSize: 40,
                        titleSize: 18,
                        titleColor: "#000"
                    },
                    content: {
                        marginT: 14,
                        marginB: 18,
                        color: "#888888",
                        size: 17
                    },
                    left: {
                        marginB: 0,
                        marginL: 10,
                        w: 135,
                        h: 50,
                        corner: 7,
                        bg: '#fff',
                        size: 16,
                        color: '#999999'
                    },
                    right: {
                        marginB: 0,
                        marginL: 30,
                        corner: 7,
                        w: 130,
                        h: 50,
                        bg: '#fff',
                        size: 16,
                        color: '#FF9014'
                    },
                    horizontalLine: {
                        color: '#DDDDDD', //（可选项）字符串类型；左右按钮上边横线的颜色，支持rgb、rgba、#；默认：'rgba(245,245,245,0)'
                        height: 1 //（可选项）数字类型；左右边按钮横线的高度；默认：0
                    },
                    verticalLine: {
                        color: '#DCDEE3', //（可选项）字符串类型；左右按钮中间竖线的颜色，支持rgb、rgba、#；默认：'rgba(245,245,245,0)'
                        width: 1 //（可选项）数字类型；左右边按钮竖线的高度；默认：0
                    }
                }
            }, function(ret) {
                var dialogBox = api.require('dialogBox');
                dialogBox.close({
                    dialogName: 'alert'
                });
                if (typeof callback === "function") {
                    callback(ret);
                }
            });
        }
        //弹出美化信息提示框
    cl.openAlert = function(params, callback) {
        var dialogBox = api.require('dialogBox');
        dialogBox.alert({
            texts: {
                title: params.title || '提示',
                content: params.content || params,
                leftBtnTitle: params.leftBtnTitle || '取消',
                rightBtnTitle: params.rightBtnTitle || '确定'
            },
            tapClose: true,
            styles: {
                bg: '#fff',
                w: 270,
                corner: 7,
                title: {
                    marginT: 12,
                    icon: params.icon || "",
                    iconSize: 40,
                    titleSize: 18,
                    titleColor: "#000"
                },
                content: {
                    marginT: 14,
                    marginB: 18,
                    color: "#888888",
                    size: 17
                },
                left: {
                    marginB: 0,
                    marginL: 0,
                    w: 135,
                    h: 50,
                    corner: 7,
                    bg: '#fff',
                    size: 16,
                    color: '#999999'
                },
                right: {
                    marginB: 0,
                    marginL: 0,
                    corner: 7,
                    w: 130,
                    h: 50,
                    bg: '#fff',
                    size: 16,
                    color: '#FF9014'
                },
                horizontalLine: {
                    color: '#DDDDDD', //（可选项）字符串类型；左右按钮上边横线的颜色，支持rgb、rgba、#；默认：'rgba(245,245,245,0)'
                    height: 1 //（可选项）数字类型；左右边按钮横线的高度；默认：0
                },
                verticalLine: {
                    color: '#DCDEE3', //（可选项）字符串类型；左右按钮中间竖线的颜色，支持rgb、rgba、#；默认：'rgba(245,245,245,0)'
                    width: 1 //（可选项）数字类型；左右边按钮竖线的高度；默认：0
                }
            }
        }, function(ret) {
            var dialogBox = api.require('dialogBox');
            dialogBox.close({
                dialogName: 'alert'
            });
            if (typeof callback === "function") {
                callback(ret);
            }
        });
    }
    cl.openSureAlert = function(params, callback) {
            var dialogBox = api.require('dialogBox');
            dialogBox.alert({
                texts: {
                    title: params.title || '提示',
                    content: params.content || params,
                    rightBtnTitle: params.rightBtnTitle || '确定'
                },
                tapClose: true,
                styles: {
                    bg: '#fff',
                    w: 270,
                    corner: 7,
                    title: {
                        marginT: 12,
                        icon: params.icon || "",
                        iconSize: 40,
                        titleSize: 18,
                        titleColor: "#000"
                    },
                    content: {
                        marginT: 14,
                        marginB: 18,
                        color: "#888888",
                        size: 17
                    },
                    right: {
                        marginB: 0,
                        marginL: 0,
                        corner: 7,
                        w: 270,
                        h: 50,
                        bg: '#fff',
                        size: 16,
                        color: '#FF9014'
                    },
                    horizontalLine: {
                        color: '#fff', //（可选项）字符串类型；左右按钮上边横线的颜色，支持rgb、rgba、#；默认：'rgba(245,245,245,0)'
                        height: 1 //（可选项）数字类型；左右边按钮横线的高度；默认：0
                    },
                    verticalLine: {
                        color: '#fff', //（可选项）字符串类型；左右按钮中间竖线的颜色，支持rgb、rgba、#；默认：'rgba(245,245,245,0)'
                        width: 0 //（可选项）数字类型；左右边按钮竖线的高度；默认：0
                    }
                }
            }, function(ret) {
                var dialogBox = api.require('dialogBox');
                dialogBox.close({
                    dialogName: 'alert'
                });
                if (typeof callback === "function") {
                    callback(ret);
                }
            });
        }
        //弹出美化图片选择弹框[单选]
    cl.openPicture = function(param, callback) {
        var dialogBox = api.require('dialogBox');
        dialogBox.scene({
            rect: {
                w: 312,
                h: 100
            },
            styles: {
                bg: '#fff',
                cell: {
                    bg: '#fff',
                    h: 48,
                    text: {
                        color: '#000',
                        size: 16
                    },
                    icon: {
                        marginL: 15,
                        marginT: 9,
                        w: 30,
                        h: 30,
                        corner: 5
                    }
                }
            },
            tapClose: true,
            optionDatas: [{
                // icon: 'widget://image/scene1.png',
                text: param.camaro
            }, {
                // icon: 'widget://image/scene2.png',
                text: param.picture
            }]
        }, function(ret, err) {
            if (ret) {
                if (ret.index == 0) {
                    var sourceType = 'camera';
                } else if (ret.index == 1) {
                    var sourceType = 'album'
                }
                var resultList = api.hasPermission({
                    list: ['storage', 'camera', 'photos']
                });
                for (var i = 0; i < resultList.length; i++) {
                    if (!resultList[i].granted) {
                        if (resultList[i].name == 'storage') {
                            api.requestPermission({
                                list: ['storage'],
                                code: 1
                            }, function(ret, err) {

                            });
                        } else if (resultList[i].name == 'camera') {
                            api.requestPermission({
                                list: ['camera'],
                                code: 1
                            }, function(ret, err) {

                            });
                        } else {
                            api.requestPermission({
                                list: ['camera'],
                                code: 1
                            }, function(ret, err) {

                            });
                        }
                    }
                }
                for (var j = 0; j < resultList.length; j++) {
                    if (resultList[j].granted && resultList[j].name == 'storage') {
                        api.getPicture({
                            sourceType: sourceType,
                            destinationType: 'url',
                            allowEdit: true,
                            quality: 50,
                            saveToPhotoAlbum: false
                        }, function(ret, err) {
                            if (ret) {
                                if (ret.data != '') {
                                    if (typeof callback === "function") {
                                        callback(ret.data);
                                    }
                                }
                            }
                        });
                    }
                }
                dialogBox.close({
                    dialogName: 'scene'
                });
            }
        });
    }

    //弹出美化图片选择弹框[多选]
    cl.openPictureM = function(param, callback) {
        var dialogBox = api.require('dialogBox');
        dialogBox.scene({
            rect: {
                w: 312,
                h: 100
            },
            styles: {
                bg: '#fff',
                cell: {
                    bg: '#fff',
                    h: 48,
                    text: {
                        color: '#000',
                        size: 16
                    },
                    icon: {
                        marginL: 15,
                        marginT: 9,
                        w: 30,
                        h: 30,
                        corner: 5
                    }
                }
            },
            tapClose: true,
            optionDatas: [{
                // icon: 'widget://image/scene1.png',
                text: param.camaro
            }, {
                // icon: 'widget://image/scene2.png',
                text: param.picture
            }]
        }, function(ret, err) {
            if (ret) {
                if (ret.index == 0) {
                    var sourceType = 'camera';
                } else if (ret.index == 1) {
                    var sourceType = 'album'
                }

                api.getPicture({
                    sourceType: sourceType,
                    destinationType: 'url',
                    allowEdit: true,
                    quality: 50,
                    saveToPhotoAlbum: false
                }, function(ret, err) {
                    if (ret) {
                        if (ret.data != '') {
                            if (typeof callback === "function") {
                                callback(ret.data);
                            }
                        }
                    }
                });
                dialogBox.close({
                    dialogName: 'scene'
                });
            }
        });
    }

    //弹出美化分享框
    cl.openShare = function(callback) {
            var imgPath = 'widget://image/';

            var dialogBox = api.require('dialogBox');
            dialogBox.share({
                rect: {
                    w: 300,
                    h: 250
                },
                items: [{
                    text: '微信',
                    icon: imgPath + 'share_wx.png'
                }, {
                    text: '朋友圈',
                    icon: imgPath + 'share_pyq.png'
                }, {
                    text: 'QQ好友',
                    icon: imgPath + 'share_qq.png'
                }, {
                    text: 'QQ空间',
                    icon: imgPath + 'share_qzone.png'
                }, {
                    text: '微博',
                    icon: imgPath + 'share-weibo.png'
                }, {
                    text: '复制链接',
                    icon: imgPath + 'share_copy.png'
                }],
                styles: {
                    bg: '#FFF',
                    maskBg: 'rgba(0,0,0,0.3)',
                    corner: 5,
                    column: 3,
                    horizontalSpace: 5,
                    verticalSpace: 20,
                    itemText: {
                        color: '#333',
                        size: 14,
                        marginT: 5
                    },
                    itemIcon: {
                        size: 60
                    }
                },
                tapClose: true
            }, function(ret) {
                var dialogBox = api.require('dialogBox');
                dialogBox.close({
                    dialogName: 'share'
                });
                if (typeof callback === "function") {
                    callback(ret);
                }
            });
        }
        //弹出美化绑定第三方手机号界面
    cl.openBindPhone = function(params, callback) {
        var dialogBox = api.require('dialogBox');
        dialogBox.input({
            keyboardType: 'default',
            texts: {
                title: params.title || '绑定账号',
                placeholder: params.placeholder || '请输入手机号',
                leftBtnTitle: '取消',
                rightBtnTitle: '确定'
            },
            styles: {
                bg: '#fff',
                // bg: '../../image/wxpay.png',
                corner: 10,
                w: 294,
                h: 161,
                title: {
                    h: 40,
                    alignment: 'center',
                    size: 18,
                    color: params.titleColor || '#000',
                    marginT: 10,
                },
                input: {
                    h: 36,
                    y: 50,
                    marginT: 10,
                    marginLeft: 20,
                    marginRight: 20,
                    textSize: 16,
                    verticalCenter: true,
                    borderColor: 'rgb(242,242,242)',
                    textColor: '#000',
                    borderWidth: 1
                },
                dividingLine: {
                    width: 0.5,
                    color: 'rgba(242,242,242,0)'
                },
                left: {
                    bg: 'rgba(0,0,0,0)',
                    color: '#999',
                    h: 50,
                    size: 14
                },
                right: {
                    bg: 'rgba(0,0,0,0)',
                    color: '#000',
                    h: 50,
                    size: 14
                },
                horizontalLine: {
                    color: 'rgba(245,245,245,.5)', //（可选项）字符串类型；左右按钮上边横线的颜色，支持rgb、rgba、#；默认：'rgba(245,245,245,0)'
                    height: 1 //（可选项）数字类型；左右边按钮横线的高度；默认：0
                },
                verticalLine: {
                    color: 'rgba(245,245,245,.5)', //（可选项）字符串类型；左右按钮中间竖线的颜色，支持rgb、rgba、#；默认：'rgba(245,245,245,0)'
                    width: 1 //（可选项）数字类型；左右边按钮竖线的高度；默认：0
                },
            },
            tapClose: true
        }, function(ret) {
            if (ret.eventType == 'right') {
                if (!cl.phoneNumberVerify.test(ret.text)) {
                    if (!cl.emailVerify.test(ret.text)) {
                        cl.toast({
                            msg: '请输入正确的手机号或者邮箱'
                        })
                    } else {
                        var dialogBox = api.require('dialogBox');
                        dialogBox.close({
                            dialogName: 'input'
                        });
                        if (typeof callback === "function") {
                            callback(ret);
                        }
                    }

                } else {
                    var dialogBox = api.require('dialogBox');
                    dialogBox.close({
                        dialogName: 'input'
                    });
                    if (typeof callback === "function") {
                        callback(ret);
                    }
                }
            }
            if (ret.eventType == 'left') {
                var dialogBox = api.require('dialogBox');
                dialogBox.close({
                    dialogName: 'input'
                });
            }
        });
    }

    //弹出美化双按钮提示框
    cl.openConfirm = function(params, callback) {
        var dialogBox = api.require('dialogBox');
        dialogBox.alert({

            texts: {
                content: params.msg || params,
                leftBtnTitle: params.leftBtnTitle || '取消',
                rightBtnTitle: params.rightBtnTitle || '确认'
            },
            styles: {
                bg: '#fff',
                w: 280,
                corner: 5,
                content: {
                    marginT: 20,
                    color: '#000',
                    size: 16
                },
                left: {
                    marginB: 10,
                    marginL: 10,
                    w: 120,
                    h: 35,
                    corner: 20,
                    bg: '#ccc',
                    color: '#fff',
                    size: 16
                },
                right: {
                    marginB: 10,
                    marginR: 10,
                    w: 120,
                    h: 35,
                    corner: 20,
                    bg: '#56C26E',
                    color: '#fff',
                    size: 16
                }
            },
            tapClose: true
        }, function(ret) {
            var dialogBox = api.require('dialogBox');
            dialogBox.close({
                dialogName: 'alert'
            });
            if (typeof callback === "function") {
                callback(ret);
            }
        });
    }

    //打开菊花加载提示
    cl.openLoading = function() {
        var imgPath = 'widget://image/refresh/';
        var activity = api.require('UILoading');
        activity.flower({
            center: { //提示框提示图标的中心点坐标
                x: api.winWidth / 2.0,
                y: api.winHeight / 2.0
            },

            size: 30, //加载提示框所处正方形的边长
            mask: 'rgba(0,0,0,0)', //遮罩层
            fixed: true //是否将模块视图固定到窗口上（不跟随窗口上下滚动）
        }, function(ret) {
            UILoadingId = ret.id;
            api.setPrefs({
                key: 'UILoading',
                value: UILoadingId
            });
            setTimeout(function() {
                cl.closeLoading(UILoadingId);
            }, 3000)
        });
        // var UILoading = api.require('UILoading');
        // UILoading.keyFrame({
        //     rect: {
        //         w: 80,
        //         h: 100
        //     },
        //     styles: {
        //         bg: 'rgba(0,0,0,0.5)',
        //         corner: 5,
        //         interval: 100,
        //         frame: {
        //             w: 50,
        //             h: 50
        //         }
        //     },
        //     content: [{
        //         "frame": "widget://image/refresh/loading.gif"
        //     },{
        //         "frame": "widget://image/refresh/loading.gif"
        //     },{
        //         "frame": "widget://image/refresh/loading.gif"
        //     },{
        //         "frame": "widget://image/refresh/loading.gif"
        //     },{
        //         "frame": "widget://image/refresh/loading.gif"
        //     },{
        //         "frame": "widget://image/refresh/loading.gif"
        //     }
        //   ],
        //     mask: 'rgba(0,0,0,0.5)'       //遮罩层配置，支持#、rgb、rgba，若不传则无遮罩层
        // });
    }

    //关闭加载提示
    cl.closeLoading = function(UILoadingId) {
        var uiloading = api.require('UILoading');
        api.getPrefs({
            key: 'UILoading'
        }, function(ret, err) {
            var v = ret.value;
            if (v === '') {
                uiloading.closeFlower({
                    id: 0 //关闭id 号对应加载提示框
                });
                uiloading.closeFlower({
                    id: UILoadingId //关闭id 号对应加载提示框
                });
            } else {
                uiloading.closeFlower({
                    id: 0 //关闭id 号对应加载提示框
                });
                uiloading.closeFlower({
                    id: UILoadingId //关闭id 号对应加载提示框
                });
                uiloading.closeFlower({
                    id: v //关闭id 号对应加载提示框
                });
            }
            api.removePrefs({
                key: 'UILoading'
            });
        });
    }
    cl.openRefreshMain = function(callback) {
            var imgPath = 'widget://image/refresh/';
            api.setCustomRefreshHeaderInfo({
                bgColor: 'rgba(0,0,0,0)',
                isScale: true,
                image: {
                    pull: [
                        imgPath + '1.png',
                        imgPath + '2.png',
                        imgPath + '3.png',
                        imgPath + '4.png',
                        imgPath + '5.png',
                        imgPath + '6.png',
                        imgPath + '7.png',
                        imgPath + '8.png',
                        imgPath + '9.png',
                        imgPath + '10.png',
                        imgPath + '11.png',
                        imgPath + '12.png',
                        imgPath + '13.png'
                    ],
                    load: [
                        imgPath + 'loading1.png',
                        imgPath + 'loading2.png',
                        imgPath + 'loading3.png',
                        imgPath + 'loading4.png',
                        imgPath + 'loading5.png',
                        imgPath + 'loading6.png',
                        imgPath + 'loading7.png',
                        imgPath + 'loading8.png',
                        imgPath + 'loading9.png',
                        imgPath + 'loading10.png',
                        imgPath + 'loading11.png',
                        imgPath + 'loading12.png'
                    ]
                }
            }, function(ret) {
                if (typeof callback === "function") {
                    callback();
                    cl.closeRefresh();
                    // setTimeout(function() {
                    //     cl.closeRefresh();
                    // }, 1000)
                }
            });
        }
        //打开下拉刷新
    cl.openRefresh = function(callback) {
        var imgPath = 'widget://image/refresh/';
        api.setCustomRefreshHeaderInfo({
            bgColor: '#eee',
            images: ['widget://image/refresh/refresh.gif'],
            tips: {
                load: '为您推荐更好的'
            },
        }, function() {
            if (typeof callback === "function") {
                callback();
                setTimeout(function() {
                    cl.closeRefresh();
                }, 1500)
            }
        });
    }

    //关闭下拉刷新
    cl.closeRefresh = function() {
        api.refreshHeaderLoadDone();
    }

    //监听上拉加载
    cl.scrollBottom = function(loadData) {
        api.addEventListener({
            name: 'scrolltobottom',
            extra: {
                threshold: -5
            }
        }, function(ret, err) {
            if (typeof loadData === "function") {
                loadData();
            }
        });
    }

    //清除HTML标签
    //@param len    是否通知截取指定长度文本
    cl.clearHTML = function(params, len) {
        params = params.replace(/<[^>]+>/g, "");
        if (len && len > 0 && params.length > len) {
            params = params.substr(0, len - 1) + '...';
        }
        return params;
    }

    //格式化日期时间
    //标准格式：2019-01-01 18:00:00
    //@param isTime 是否返回时间部分
    cl.formatDate = function(params, isTime) {
        var date = new Date(params);
        var y = date.getFullYear();
        var m = date.getMonth() + 1;
        var d = date.getDate();
        var info = add0(y) + '-' + add0(m) + '-' + add0(d);

        if (isTime) {
            var hour = date.getHours();
            var minute = date.getMinutes();
            var second = date.getSeconds();
            info += ' ' + add0(hour) + ':' + add0(minute) + ':' + add0(second);
        }

        function add0(m) {
            return m < 10 ? '0' + m : m
        }

        return info;
    }

    //验证手机号格式
    cl.isPhoneNum = function(params) {
        return /^1[123456789]\d{9}$/.test(params)
    }

    //返回完整的图片URL
    cl.getImgUrl = function(params) {
        return apiServer + params;
    }

    //检测处理input 释放焦点
    //@param obj    是否为空，否则弹出msg提示
    //@param obj2   是否与obj一致，否则弹出msg2提示
    cl.chkField = function(params) {
        params.obj.blur();
        var val = params.obj.value;
        if (!val) {
            cl.toast(params.msg);
            return;
        } else if (params.obj2) {
            params.obj2.blur();
            var val2 = params.obj2.value;
            if (val != val2) {
                cl.toast(params.msg2);
                return;
            } else {
                return val;
            }
        } else {
            return val;
        }
    }

    //用户注销处理
    cl.loginOut = function() {
        $api.clearStorage();
        api.rebootApp();
    }

    //控制台带时间打印日志
    cl.log = function(params) {
        if (typeof params === 'object') {
            params = $api.jsonToStr(params);
        }
        var time = cl.formatDate(new Date(), true);
        console.log('[' + time + '] ' + params);
    }

    //下拉选择框
    cl.openSelector = function(col, data, fn) {
        var UIActionSelector = api.require('UIActionSelector');
        UIActionSelector.open({
            datas: data,
            layout: {
                rowSpacing: 7,
                col: col,
                size: 15,
                sizeActive: 17,
                color: '#000000',
                colorSelected: '#000000',
                color: '#666',
                colorSelected: '#000000',
                colorActive: '#000',
                maskBg: 'rgba(0,0,0,0.2)',
            },
            animation: true,
            selectorDividerColor: 'rgba(255,255,255,0)',
            cancel: {
                text: '取消',
                size: 16,
                color: '#B3B0A1',
                colorActive: '#B3B0A1',
                bg: '#fff',
                bgActive: '#fff',
            },
            ok: {
                text: '确定',
                size: 16,
                color: '#231916',
                colorActive: '#231916',
                bg: '#fff',
                bgActive: '#fff',
            },
            title: {
                text: '',
                color: '#000000',
                size: 16,
                bg: '#fff',
            },
            fixedOn: api.frameName
        }, function(ret, err) {
            fn(ret);
        });
    }

    //下拉选择框
    cl.openSelectorTwo = function(col, data, title, fn) {
        var UIActionSelector = api.require('UIActionSelector');
        UIActionSelector.open({
            datas: data,
            layout: {
                rowSpacing: 7,
                col: col,
                size: 16,
                sizeActive: 17,
                color: '#E2E2E2',
                colorSelected: '#000000',
                colorActive: '#000',
                maskBg: 'rgba(0,0,0,0.2)',
            },
            animation: true,
            selectorDividerColor: '#fff',
            cancel: {
                text: '取消',
                size: 16,
                color: '#B3B0A1',
                bgActive: '#fff'
            },
            ok: {
                text: '确定',
                size: 16,
                color: '#333',
                bgActive: '#fff'
            },
            title: {
                text: title,
                color: '#000000',
                size: 16,
                bg: '#fff',
            },
            fixedOn: api.frameName
        }, function(ret, err) {
            fn(ret);
        });
    }

    /**
     * [打印alert信息 description]
     * @type {[type]}
     */
    cl.jsonAlert = function(json, tip) {
        tip = tip || '';
        str = JSON.stringify(json);
        str = str.replace(/,/g, ",\n")
        alert(tip + str);
    };
    cl.nickVerify = /^[\u4E00-\u9FA5a-zA-Z0-9_]*$/; //昵称校验
    cl.passwordVerify = /^[A-Za-z0-9]{6,12}$/; // 密码校验6-12位字母或数字组合。

    cl.numberVerify = /^\d+$/; //纯数字校验

    cl.phoneNumberVerify = /^[1](([3][0-9])|([4][5-9])|([5][0-3,5-9])|([6][5,6])|([7][0-8])|([8][0-9])|([9][1,8,9]))[0-9]{8}$/; //手机号校验

    cl.emailVerify = /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/; //邮箱验证

    cl.IDnumberVerify = /(^\d{15}$)|(^\d{17}([0-9]|X)$)/; //身份证号验证

    cl.truenameVerify = /^[0-9\a-zA-Z\u4E00-\u9FA5\uF900-\uFA2D\u00B7\u2022\u0095\u0387(.)]+$/; //真实姓名验证
    cl.companyVerify = /^[0-9\a-zA-Z\u4E00-\u9FA5\uF900-\uFA2D\u00B7\u2022\u0095\u0387]+$/; //公司名称

    cl.taxVerify = /^(?![a-zA-Z]+$)[0-9A-Za-z]{1,20}$/; //税号验证

    cl.nickNameVerify = /^[a-zA-Z\d\u4e00-\u9fa5]{1,11}$/; // 昵称验证
    cl.postal = /^[1-9][0-9]{5}$/; //验证邮政编码
    /*end*/
    window.cl = cl;

})(window);
